<?php

namespace App\Service\WorkOrder\Web;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\WorkOrder\ErrCode;
use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Form\Form;
use App\Http\Form\KfCashRegisterV2\KfCashRegisterV2FormAttribute;
use App\Http\Middleware\OpenShop\FeishuWebAuth;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Jobs\FuYou\FuYouAutoJob;
use App\Jobs\FuYou\FuYouSendEmailAutoJob;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ConfigModel;
use App\Models\FuYou\WorkOrderFuyouInfoModel;
use App\Models\FuYou\WorkOrderFuyouLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderApplyManagerSubmitHistoryModel;
use App\Models\WorkOrder\WorkOrderMissionModel;
use App\Models\WorkOrder\WorkOrderOperateLogModel;
use App\Models\WorkOrder\WorkOrderRejectModel;
use App\Models\WorkOrder\WorkOrderResetModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Remote\Orm\OrmShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use App\Service\Common\EmailService;
use App\Service\FuYou\FuYouService;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\SiteLocation\SiteLocationService;
use App\Service\System\SystemNotifyService;
use App\Service\WorkOrder\Message\SendFsService;
use App\Service\WorkOrder\Message\SendSmsService;
use App\Service\WorkOrder\Mission\MissionEngineService;
use App\Service\WorkOrder\Mission\MissionNoticeService;
use App\Support\ChangeSupport;
use App\Support\CustomForm\AttributeWorkOrderSupport;
use App\Support\FeishuMsgSupport;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class ApplyService extends BaseService
{

    const SEND_EMAIL_TYPE_SECONDARY_BINDING = 1;//重新发送一二级绑定邮件
    const SEND_EMAIL_TYPE_SYSTEM_APPLY      = 2;//重新发送前置系统申请邮件

    /**
     * 工单详情
     *
     * @param string $workOrderNo
     * @return array|void
     * @throws GuzzleException
     * @throws Exception
     */
    public static function mainDetail(string $workOrderNo, int $userId)
    {
        try {
            $applyMain = WorkOrderApplyMainModel::getDetailByWorkOrderNo($workOrderNo, true);

            $applyMainExtra = collect($applyMain->extra ? json_decode($applyMain->extra) : new \stdClass());
            $shopInfo       = (object)current((new RmsShopApi())->getShopByIds([$applyMain->shopId])["data"]["shopList"]);
            if (!$applyMainExtra->get("mobile")) {
                $applyMainExtra = $applyMainExtra->merge(["mobile" => $shopInfo->shopMobile]);
                $applyMain->update(["extra" => $applyMainExtra->toJson(JSON_UNESCAPED_UNICODE)]);
            }

            $manager = OrganizationManageService::getOrganizationInfoByType(
                OrganizationManageEnum::TYPE_BRANCH_OFFICE,
                $shopInfo->province
            );

            $progress  = (new MissionEngineService($applyMain))->webShowProgress();
            $signOrder = OpenShopSignOrderModel::query()->where("shopCode", $shopInfo->shopCode)->first();

            $operationUid      = $manager["operationUid"] ?? 0;
            $supervisorUid     = $signOrder && $signOrder->checkAcceptRel ? $signOrder->checkAcceptRel->managerId ?? 0 : 0;
            $fuyouLogUpdateIds = collect($applyMain->fuyouLogRel)->pluck('updatedByUid')->toArray();//富友自动进件日志记录表-管理员id
            $userIds           = array_filter(array_merge([
                $applyMain->createdByUid,
                $operationUid,
                $supervisorUid,
                $shopInfo->councilorId
            ], $fuyouLogUpdateIds));
            $userInfo          = collect($userIds ? RmsUserRemote::getRmsUserByIds($userIds) : [])->pluck(null, "id");

            //获取任务信息
            $resolvedMissions = WorkOrderMissionModel::progressResolve($workOrderNo, $progress);
            $handleUsername   = $resolvedMissions->get($applyMain->step) ?
                collect($resolvedMissions->get($applyMain->step)["handle"])->implode("managerName", ",") : "";

            $isToday        = (date("Y-m-d", time()) == formatDateYmd($applyMain->createdAt->timestamp));
            $progressDetail = collect($progress)->map(function ($v) use ($resolvedMissions, $applyMain, $userInfo) {
                if ($mission = $resolvedMissions->get($v)) {
                    return $mission;
                } else {
                    switch ($v) {
                        case MissionEnum::STEP_1:
                            return [
                                "step"     => MissionEnum::STEP_1,
                                "stepDesc" => MissionEnum::STEP_TEXT[MissionEnum::STEP_1],
                                "handle"   => [
                                    [
                                        "id"            => 0,
                                        "role"          => 0,
                                        "roleDesc"      => "",
                                        "dealUid"       => $applyMain->createdByUid,
                                        "missionStatus" => MissionEnum::MISSION_STATUS_1,
                                        "completeTime"  => formatDate($applyMain->createdAt->timestamp, ""),
                                        "managerName"   => $userInfo->get($applyMain->createdByUid)["username"] ?? ""
                                    ]
                                ]
                            ];
                            break;
                        case MissionEnum::STEP_7:
                            return [
                                "step"     => MissionEnum::STEP_7,
                                "stepDesc" => MissionEnum::STEP_TEXT[MissionEnum::STEP_7],
                                "handle"   => [
                                    [
                                        "id"            => 0,
                                        "role"          => 0,
                                        "roleDesc"      => "",
                                        "dealUid"       => 0,
                                        "missionStatus" => optional($applyMain->fuyouInfoRel)->status == MissionEnum::MISSION_STATUS_1 ? MissionEnum::MISSION_STATUS_1 : MissionEnum::MISSION_STATUS_0,
                                        "completeTime"  => '',
                                        "managerName"   => "",
                                    ]
                                ]
                            ];
                            break;
                        case MissionEnum::STEP_8:
                            return [
                                "step"     => MissionEnum::STEP_8,
                                "stepDesc" => MissionEnum::STEP_TEXT[MissionEnum::STEP_8],
                                "handle"   => [
                                    [
                                        "id"            => 0,
                                        "role"          => 0,
                                        "roleDesc"      => "",
                                        "dealUid"       => 0,
                                        "missionStatus" => 0,
                                        "completeTime"  => '',
                                        "managerName"   => "",
                                        "wxStatus"      => optional($applyMain->fuyouInfoRel)->weChatAuthorizeStatus ?? 0,
                                        //微信认证状态
                                        "aliPayStatus"  => optional($applyMain->fuyouInfoRel)->alipayAuthorizeStatus ?? 0,
                                        //支付宝认证状态
                                    ]
                                ]
                            ];
                            break;
                        case MissionEnum::STEP_99:
                            return [
                                "step"     => MissionEnum::STEP_99,
                                "stepDesc" => MissionEnum::STEP_TEXT[MissionEnum::STEP_99],
                                "handle"   => [
                                    [
                                        "id"            => 0,
                                        "role"          => 0,
                                        "roleDesc"      => "",
                                        "dealUid"       => 0,
                                        "missionStatus" => $applyMain->step == MissionEnum::STEP_100 ? MissionEnum::MISSION_STATUS_1 : MissionEnum::MISSION_STATUS_0,
                                        "completeTime"  => formatDate($applyMain->completeTime, ""),
                                        "managerName"   => ""
                                    ]
                                ]
                            ];
                            break;
                        default:
                            return [
                                "step"     => $v,
                                "stepDesc" => MissionEnum::STEP_TEXT[$v],
                                "handle"   => [
                                    [
                                        "id"            => 0,
                                        "role"          => 0,
                                        "roleDesc"      => "",
                                        "dealUid"       => 0,
                                        "missionStatus" => MissionEnum::MISSION_STATUS_0,
                                        "completeTime"  => "",
                                        "managerName"   => "",
                                    ]
                                ]
                            ];
                            break;
                    }
                }
            })->map(function ($v) use ($isToday, $workOrderNo, $userId) {
                $v["handle"] = collect($v["handle"])->map(function ($handle) use ($isToday, $workOrderNo, $v, $userId) {
                    $showNoticeBtn = false;
                    $canNotice     = false;
                    if ($handle["missionStatus"] == MissionEnum::MISSION_STATUS_0 && $handle["id"] > 0) {
                        $showNoticeBtn = true;
                        if (
                            !$isToday
                            &&
                            !MissionNoticeService::isWebPressNoticedToday($workOrderNo, $v["step"],
                                FeishuWebAuth::$userId, $handle["dealUid"])
                            &&
                            $handle["dealUid"] != $userId
                        ) {
                            $canNotice = true;
                        }
                    }
                    return array_merge($handle, [
                        "showNoticeBtn" => $showNoticeBtn,
                        "canNotice"     => $canNotice,
                    ]);
                });
                return $v;
            })->toArray();

            // 用户角色
            $roles = WorkOrderUserRoleModel::query()->where('userId', $userId)->pluck('role')->toArray();

            if (in_array($applyMain->problemPid, [OrderEnum::PROBLEM_PID_1, OrderEnum::PROBLEM_PID_2])) {
                $ormShopInfo = OrmShopRemote::getStoreByShopId($applyMain->shopId)["data"];
                $shopName    = $ormShopInfo ? ($ormShopInfo["name"] ?? "") : "";
            } else {
                $shopName = "{$shopInfo->shopCode}{$shopInfo->name}";
            }
            $fuyouAuditStatus = WorkOrderFuyouInfoModel::DEFAULT_STATUS;//富友审核状态
            if ($applyMain->problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105 && $applyMain->step >= MissionEnum::STEP_8) {//大于此步骤代表富友资料审核完成
                $fuyouAuditStatus = WorkOrderFuyouInfoModel::DEFAULT_SUC_STATUS;
            }
            $mode = attributeGet($applyMain,  "openShopMainProcessRel.signOrderRel.contractRel.mode", 0);

            // 分账模式工单自动带入「厦门心有炸念」账号信息（商户号 密钥 前缀）
            if ($mode == OpenShopContractTemplateModel::MODE_2) {
                $getConfig   = ConfigModel::getFuyouCompanyConfig();
                $fyMchntCd   = $getConfig['fyMchntCd'] ?? '';
                $mchKey      = $getConfig['mchKey'] ?? '';
                $orderPrefix = $getConfig['orderPrefix'] ?? '';
            } else {
                $fyMchntCd   = optional($applyMain->fuyouInfoRel)->fyMchntCd ?? '';
                $mchKey      = optional($applyMain->fuyouInfoRel)->mchKey ?? '';
                $orderPrefix = optional($applyMain->fuyouInfoRel)->orderPrefix ?? '';
            }

            // 非法人收款标记
            $tags          = [];// 前端显示标记数组
            $unCorporation = 0;// 默认0 2-非法人
            $payeeType     = WorkOrderApplyContentModel::getContent($applyMain->contentRel)
                ->get('payeeType', 0);
            if ($payeeType == KfCashRegisterV2FormAttribute::PAYEE_TYPE_UN_CORPORATION) {// 其他人收款
                $unCorporation = KfCashRegisterV2FormAttribute::PAYEE_TYPE_UN_CORPORATION;
                $tags[]        = '非法人';
            }
            return [
                "grabButton"      => OrderListService::showGrab($applyMain, $userId, $roles),
                'transferButton'  => (int)(new MissionEngineService($applyMain))->checkTransfer($userId),
                "enums"           => [
                    "role" => collect(OrderEnum::PRIORITY_TEXT)->map(function ($v, $k) {
                        if (is_int($k) && $k > 0) {
                            return [
                                "key" => $k,
                                "val" => $v
                            ];
                        }
                    })->filter()->values()->toArray()
                ],
                "applyMain"       => [
                    "workOrderNo"    => $applyMain->workOrderNo,
                    "shopPattern"    => 0,
                    "shopPatternStr" => '',
                    "patternType"    => '',
                    "patternTypeStr" => '',
                    'tagLocation'    => optional($applyMain->openShopMainProcessRel)->openShopSiteLocationRel && SiteLocationService::tagLocationStatus(optional($applyMain->openShopMainProcessRel)->openShopSiteLocationRel),
                    "createdAt"      => formatDate($applyMain->createdAt->timestamp, "-"),
                    "updatedAt"      => formatDate($applyMain->updatedAt->timestamp, "-"),
                    "problemPidText" => (OrderEnum::PROBLEM_PID_TEXT[$applyMain->problemPid] ?? '-') . '-' . (OrderEnum::TYPE_RELATION_MAP[$applyMain->problemPid][$applyMain->problemChildId] ?? '-'),
                    "problemPid"     => $applyMain->problemPid,
                    "problemChildId" => $applyMain->problemChildId,
                    "createdByUid"   => $applyMain->createdByUid,
                    "priority"       => $applyMain->priority,
                    "createUsername" => $userInfo->get($applyMain->createdByUid) ? $userInfo->get($applyMain->createdByUid)["username"] : "",
                    "createMobile"   => $userInfo->get($applyMain->createdByUid) ? $userInfo->get($applyMain->createdByUid)["mobile"] : "",
                    //创建人手机号
                    "submitUsername" => $userInfo->get($applyMain->createdByUid) ? $userInfo->get($applyMain->createdByUid)["username"] : "",
                    //提交人
                    "submitMobile"   => $userInfo->get($applyMain->createdByUid) ? $userInfo->get($applyMain->createdByUid)["mobile"] : "",
                    //提交人手机号
                    "handleUsername" => $handleUsername,
                    "nowStep"        => $applyMain->step,
                    'childStep'      => $applyMain->childStep,
                    'sourceType'     => $applyMain->sourceType,
                    'sourceTypeText' => WorkOrderApplyMainModel::SOURCE_TYPE_TEXT[$applyMain->sourceType] ?? "",
                    'mode'           => $mode,
                    'modeText'       => OpenShopContractTemplateModel::MODE_MAP_TEXT[$mode]?? "-",
                    'unCorporation'  => $unCorporation,
                    'tags'           => $tags,// 标签
                ],
                "processProgress" => $progressDetail,
                "shopInfo"        => [
                    "shopName"              => $shopName,
                    "shopAddress"           => $shopInfo->addressPrefix . $shopInfo->address,
                    "mobile"                => $applyMainExtra->get("mobile"),
                    "franchisee"            => $signOrder && $signOrder->identityCardRel ? $signOrder->identityCardRel->name : "",
                    "supervisor"            => $userInfo->get($shopInfo->councilorId, [])["username"] ?? "",
                    "supervisorMobile"      => $userInfo->get($shopInfo->councilorId, [])["mobile"] ?? "",
                    "provincialTotalMobile" => $userInfo->get($manager["operationUid"] ?? 0)["mobile"] ?? "",
                    "provincialTotal"       => $manager["operationName"] ?? "",
                    "addressPrefix"         => $shopInfo->addressPrefix,
                    //门店区域 省市区
                    "branch"                => $shopInfo->branch,
                    //分公司
                    "id"                    => $shopInfo->id,
                    //门店id
                    "shopCode"              => $shopInfo->shopCode,
                    //门店编码
                    "payments"              => $shopInfo->shop_fu_you_payments_rel ? ['id' => optional($shopInfo->shop_fu_you_payments_rel)['id']] : ['id' => 0],
                    //店铺支付配置表-前端做修改还是新增使用
                ],
                "fuyouInfo"       => [//富友信息
                    "id"                     => optional($applyMain->fuyouInfoRel)->id,
                    "status"                 => $fuyouAuditStatus,
                    //审核状态
                    "weChatAuthorizeImg"     => optional($applyMain->fuyouInfoRel)->weChatAuthorizeImg,
                    //微信授权二维码图片
                    "wxStatus"               => optional($applyMain->fuyouInfoRel)->weChatAuthorizeStatus,
                    //微信认证状态
                    "aliPayAuthorizeImg"     => optional($applyMain->fuyouInfoRel)->alipayAuthorizeImg,
                    //支付宝授权二维码图片
                    "aliPayStatus"           => optional($applyMain->fuyouInfoRel)->alipayAuthorizeStatus,
                    //支付宝认证状态
                    "auditMsg"               => optional($applyMain->fuyouInfoRel)->status,
                    //审核返回信息
                    "fyMchntCd"              => $fyMchntCd,
                    //商户号
                    "mchKey"                 => $mchKey,
                    //富友商户交易密码
                    "orderPrefix"            => $orderPrefix,
                    //富友商户交易前缀
                    "imgList"                => optional($applyMain->fuyouInfoRel)->shopImg ? json_decode(optional($applyMain->fuyouInfoRel)->shopImg,
                        true) : [],
                    //商户图片列表-三张图
                    "mchName"                => optional($applyMain->fuyouInfoRel)->mchName,
                    //富友商户用户名
                    "mchPassword"            => optional($applyMain->fuyouInfoRel)->mchPassword,
                    //富友商户密码
                    "secondaryBindingStatus" => optional($applyMain->fuyouInfoRel)->secondaryBindingStatus,
                    //富友一二级绑定邮件状态 0默认待认证 1成功 2失败
                    "preSystemApplyStatus"   => optional($applyMain->fuyouInfoRel)->preSystemApplyStatus,
                    //富友前置系统申请邮件状态 0默认待认证 1成功 2失败
                    "reservedFyTermId"   => optional($applyMain->fuyouInfoRel)->reservedFyTermId,
                    //富友终端号
                ],
                "auditLog"        => collect($applyMain->fuyouLogRel)->map(
                    function ($v) use ($userInfo) {
                        $res = json_decode($v['res'], true);
                        if ($res) {
                            if (isset($res['msg'])) {
                                $res = $res['msg'];
                            } elseif (isset($res['retMsg'])) {
                                $res = $res['retMsg'];
                            }
                        }
                        return [
                            "id"           => $v['id'],
                            "status"       => $v['status'],
                            "res"          => $res,
                            "updatedByUid" => $v['updatedByUid'],
                            "managerName"  => $userInfo->get($v['updatedByUid'])["username"] ?? "",
                            "createdAt"    => formatDate(strtotime($v['createdAt'])),
                        ];
                    }
                )->toArray(),//富友审核记录信息
            ];

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @param string $workOrderNo
     * @return array|void
     * @throws Exception
     */
    public static function contentDetail(string $workOrderNo)
    {
        try {
            $applyMain = WorkOrderApplyMainModel::getDetailByWorkOrderNo($workOrderNo, true);
            AttributeWorkOrderSupport::setApplyMainModel('', $applyMain);

            switch ($applyMain->problemPid) {
                case OrderEnum::PROBLEM_PID_5:
                    $formContent = Form::getFormContentByApplyMainModel($applyMain);
                    break;
                case OrderEnum::PROBLEM_PID_1:
                case OrderEnum::PROBLEM_PID_2:
                case OrderEnum::PROBLEM_PID_4:
                case OrderEnum::PROBLEM_PID_6:
                case OrderEnum::PROBLEM_PID_7:
                case OrderEnum::PROBLEM_PID_8:
                case OrderEnum::PROBLEM_PID_9:
                case OrderEnum::PROBLEM_PID_10:
                    $formContent = ProblemFeedbackWebService::getWorkOrderInfo($workOrderNo) ?? [];
                    break;
                default:
                    throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null,
                        "未配置的表单分类体 【{$applyMain->problemPid}】");
            }

            return [
                "merchantConfirmStatus" => $applyMain->merchantConfirmFinishStatus,
                "form"                  => $formContent,
                "feedback"              => ProblemFeedbackWebService::handleProcedureInfo($applyMain),
                "operateHistory"        => WorkOrderOperateLogModel::query()
                                                                   ->where("workOrderNo", $workOrderNo)
                                                                   ->orderByDesc("id")->get()
                                                                   ->map(function (
                                                                       WorkOrderOperateLogModel $operateLogModel
                                                                   ) {
                                                                       return [
                                                                           "step"            => $operateLogModel->step,
                                                                           "stepText"        => MissionEnum::STEP_TEXT[$operateLogModel->step] ?? "-",
                                                                           "type"            => $operateLogModel->type,
                                                                           "typeText"        => WorkOrderOperateLogModel::TYPE_TEXT[$operateLogModel->type] ?? "-",
                                                                           "content"         => $operateLogModel->content,
                                                                           "createdUsername" => $operateLogModel->createdUsername,
                                                                           "createdAt"       => $operateLogModel->createdAt->format("Y-m-d H:i:s"),
                                                                       ];
                                                                   })->toArray()
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 修改优先级
     *
     * @param string $workOrderNo
     * @param int $priority
     * @throws Exception
     */
    public static function updatePriority(string $workOrderNo, int $priority)
    {
        try {
            WorkOrderApplyMainModel::query()->where("workOrderNo", $workOrderNo)
                                   ->update([
                                       "priority"  => $priority,
                                       "updatedAt" => time()
                                   ]);
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 更新门店手机号
     *
     * @param string $workOrderNo
     * @param string $mobile
     * @throws Exception
     */
    public static function updateShopMobile(string $workOrderNo, string $mobile)
    {
        try {
            $applyMainDetail = WorkOrderApplyMainModel::query()->where("workOrderNo", $workOrderNo)->first();

            $applyMainDetail->setRawAttributes([
                "extra"     => collect($applyMainDetail->extra ? json_decode($applyMainDetail->extra) : new \stdClass())
                    ->merge(["mobile" => $mobile])
                    ->toJson(JSON_UNESCAPED_UNICODE),
                "updatedAt" => time()
            ]);
            $applyMainDetail->save();
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @param object $params
     * @throws ValidationException
     */
    public static function submitRemark(object $params)
    {
        try {
            $applyManagerDetail = WorkOrderApplyManagerModel::query()->where("id", $params->id)->first();
            $mainApply          = WorkOrderApplyMainModel::query()->where('workOrderNo', $params->workOrderNo)->first();

            $step = null;
            $type = null;
            switch ($applyManagerDetail->role) {
                case WorkOrderUserRoleModel::ROLE_TYPE_1:
                case WorkOrderUserRoleModel::ROLE_TYPE_6:
                    $step = MissionEnum::STEP_2;
                    $type = WorkOrderOperateLogModel::TYPE_4;
                    break;
                case WorkOrderUserRoleModel::ROLE_TYPE_7:
                    $step = MissionEnum::STEP_4;
                    $type = WorkOrderOperateLogModel::TYPE_6;
                    break;
                default:
                    if ($mainApply->isFunctionWaiMaiOpen()) {
                        $step = MissionEnum::STEP_5;
                        $type = WorkOrderOperateLogModel::TYPE_8;
                    } else {
                        //富友自动进件
                        if ($mainApply->problemChildId != OrderEnum::PROBLEM_PID_5_CHILDREN_105) {
                            $step = MissionEnum::STEP_4;
                            $type = WorkOrderOperateLogModel::TYPE_6;
                        } else {
                            $step = $mainApply->step;
                            $type = WorkOrderOperateLogModel::TYPE_3;
                        }
                    }
                    break;
            }

            WorkOrderOperateLogModel::query()->insert([
                "workOrderNo"     => $applyManagerDetail->workOrderNo,
                "step"            => $step,
                "type"            => $type,
                "content"         => $params->remark,
                "createdByUid"    => request()->user()->id,
                "createdUsername" => request()->user()->username,
                "createdAt"       => time()
            ]);

            WorkOrderApplyManagerSubmitHistoryModel::query()->insert([
                "applyManagerId"  => $applyManagerDetail->id,
                "type"            => WorkOrderApplyManagerSubmitHistoryModel::TYPE_REMARK,
                "content"         => $params->remark,
                "createdByUid"    => request()->user()->id,
                "createdUsername" => request()->user()->username,
                "createdAt"       => time()
            ]);

            $applyManagerDetail->update(["remark" => $params->remark]);

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @param object $params
     * @throws ValidationException
     */
    public static function submitSolution(object $params)
    {
        try {
            $applyManagerDetail = WorkOrderApplyManagerModel::query()->where("id", $params->id)->first();
            $mainApply          = WorkOrderApplyMainModel::query()->where('workOrderNo', $params->workOrderNo)->first();

            $step = null;
            $type = null;
            switch ($applyManagerDetail->role) {
                case WorkOrderUserRoleModel::ROLE_TYPE_1:
                case WorkOrderUserRoleModel::ROLE_TYPE_6:
                    $step = MissionEnum::STEP_2;
                    $type = WorkOrderOperateLogModel::TYPE_3;
                    break;
                case WorkOrderUserRoleModel::ROLE_TYPE_7:
                    $step = MissionEnum::STEP_4;
                    $type = WorkOrderOperateLogModel::TYPE_5;
                    break;
                default:
                    if ($mainApply->isFunctionWaiMaiOpen()) {
                        $step = MissionEnum::STEP_5;
                        $type = WorkOrderOperateLogModel::TYPE_7;
                    } else {
                        //富友自动进件
                        if ($mainApply->problemChildId != OrderEnum::PROBLEM_PID_5_CHILDREN_105) {
                            $step = MissionEnum::STEP_4;
                            $type = WorkOrderOperateLogModel::TYPE_5;
                        } else {
                            dispatch((new FuYouAutoJob([
                                'workOrderNo' => $params->workOrderNo,
                                'id'          => $params->id,
                                'shopId'      => $mainApply->shopId
                            ])))->onQueue('{fuyou-auto}');
                            $step = $mainApply->step;
                            $type = WorkOrderOperateLogModel::TYPE_5;
                        }
                    }
                    break;
            }

            WorkOrderOperateLogModel::query()->insert([
                "workOrderNo"     => $applyManagerDetail->workOrderNo,
                "step"            => $step,
                "type"            => $type,
                "content"         => $params->solution,
                "createdByUid"    => request()->user()->id,
                "createdUsername" => request()->user()->username,
                "createdAt"       => time()
            ]);

            WorkOrderApplyManagerSubmitHistoryModel::query()->insert([
                "applyManagerId"  => $applyManagerDetail->id,
                "type"            => WorkOrderApplyManagerSubmitHistoryModel::TYPE_SOLUTION,
                "content"         => $params->solution,
                "createdByUid"    => request()->user()->id,
                "createdUsername" => request()->user()->username,
                "createdAt"       => time()
            ]);

            $applyManagerDetail->update(["solution" => $params->solution]);

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 提交
     *
     * @param int $id
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function submit(int $id)
    {
        try {
            $applyManagerDetail = WorkOrderApplyManagerModel::query()->where("id", $id)->first();
            $workOrderNo        = $applyManagerDetail->workOrderNo;
            $mainApply          = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();

            $checkSolutionFunc = function () use ($applyManagerDetail) {
                if (empty($applyManagerDetail->solution)) {
                    throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "当前处理阶段解决方案缺失");
                }
            };

            $checkRemarkFunc = function () use ($applyManagerDetail) {
                if (empty($applyManagerDetail->remark)) {
                    throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "当前处理阶段备注缺失");
                }
            };

            switch ($applyManagerDetail->role) {
                case WorkOrderUserRoleModel::ROLE_TYPE_1:
                    // 需要指派负责人
                    if (!in_array($mainApply->problemPid, OrderEnum::GRAB_PIDS)) {
                        $role = OrderEnum::PROBLEM_PID_TO_ROLE[$mainApply->problemPid] ?? 0;
                        if (WorkOrderApplyManagerModel::query()->where('workOrderNo', $applyManagerDetail->workOrderNo)
                                                      ->where('role', $role)->count() == 0) {
                            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "未指派负责人，无法提交");
                        }
                    }

                    $checkRemarkFunc();

                    // 新增问题工单-提交到下一步
                    if (in_array($mainApply->problemPid, OrderEnum::NEW_GRAB_PIDS)) {
                        (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_4);
                    } else {
                        (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_2);
                    }
                    break;
                case WorkOrderUserRoleModel::ROLE_TYPE_6:
                    $checkSolutionFunc();
                    (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_2);
                    break;
                case WorkOrderUserRoleModel::ROLE_TYPE_7:
                    $checkSolutionFunc();
                    (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_4);
                    break;
                default:
                    if ($mainApply->problemChildId != OrderEnum::PROBLEM_PID_5_CHILDREN_105) {//夸父收银进件2.0可多次提交
                        $checkSolutionFunc();
                    }

                    if ($mainApply->step == MissionEnum::STEP_2) {
                        $checkRemarkFunc();
                    }

                    // 所有负责人都提交了，推送任务
                    if (WorkOrderApplyManagerModel::query()
                                                  ->where("role", "<>", WorkOrderUserRoleModel::ROLE_TYPE_1)
                                                  ->where('workOrderNo', $workOrderNo)
                                                  ->where("status", WorkOrderApplyManagerModel::STATUS_ON)
                                                  ->get()
                                                  ->where('solution', '')
                                                  ->count() == 0) {
                        if ($mainApply->isFunctionWaiMaiOpen()) {
                            (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_5);
                        } else {
                            //富友自动进件
                            if ($mainApply->problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105) {
//                                dispatch((new FuYouAutoJob([
//                                    'workOrderNo' => $workOrderNo,
//                                    'id'          => $id,
//                                    'shopId'      => $mainApply->shopId
//                                ])))->onQueue('{fuyou-auto}');
                                break;
                            } else {
                                (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_4);
                            }
                        }
                        // 消息中心推送
                        $problemPidText     = $mainApply->problemPidText;
                        $problemChildIdText = $mainApply->problemChildIdText;

                        $title     = '您提交的工单已处理完成';
                        $summary   = "尊敬的夸父伙伴您好，你提交的{$problemPidText}-{$problemChildIdText}工单，已处理完成，请点击查看详情。";
                        $shopId    = $mainApply->shopId;
                        $fsMsgSend = function () use ($workOrderNo, $title, $summary, $shopId) {
                            $pushUidMap = array_values(
                                array_column(
                                    (RmsUserRemote::getShopManagerUserByShopId([$shopId])['lists'] ?? []),
                                    "userId"
                                )
                            );

                            SystemNotifyService::customerBatchPush(
                                $pushUidMap,
                                $title,
                                $summary,
                                config('webUrl.notify_web_cdn_url') . '#/pages/work-order/feedback/progress-detail?id=' . $workOrderNo,
                                $shopId,
                                SystemNotifyCenterModel::NOTIFY_TYPE_5
                            );
                        };

                        if ($mainApply->sourceType == WorkOrderApplyMainModel::SOURCE_TYPE_0) {
                            $fsMsgSend();
                        }
                    }
                    break;
            }

            $applyManagerDetail->update(["submitTime" => time()]);
            $mainApply->update(["childStep" => 0]);
            WorkOrderRejectModel::saveStatus($workOrderNo, WorkOrderRejectModel::STATUS_OK, $mainApply->step);

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 备注｜解决方案提交
     *
     * @param int $id
     * @param string $remark
     * @param string $solution
     * @throws Exception
     */
    public static function submitRemarkAndSolution(int $id, string $remark, string $solution)
    {
        try {
            $applyManagerDetail = WorkOrderApplyManagerModel::query()->where("id", $id)->first();
            $workOrderNo        = $applyManagerDetail->workOrderNo;
            $mainApply          = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();
            if (!$mainApply) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "找不到对应的工单");
            }

            switch ($applyManagerDetail->role) {
                case WorkOrderUserRoleModel::ROLE_TYPE_1:
                    if (empty($remark)) {
//                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "备注不能为空");
                        $remark = "-";
                    }

                    if ($applyManagerDetail->remark) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "客服备注已提交，请勿反复操作！");
                    }

                    // 需要指派负责人
                    if (!in_array($mainApply->problemPid, OrderEnum::GRAB_PIDS)) {
                        $role = OrderEnum::PROBLEM_PID_TO_ROLE[$mainApply->problemPid] ?? 0;
                        if (WorkOrderApplyManagerModel::query()->where('workOrderNo', $applyManagerDetail->workOrderNo)
                                                      ->where('role', $role)->count() == 0) {
                            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "未指派负责人，无法提交");
                        }
                    }

                    $update = ["remark" => $remark];
                    $applyManagerDetail->update($update);

                    (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_2);

                    break;
                case WorkOrderUserRoleModel::ROLE_TYPE_6:
                    if (empty($remark)) {
                        $remark = "-";
//                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "备注不能为空");
                    }
                    if ($applyManagerDetail->remark) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "客服备注已提交，请勿反复操作！");
                    }

                    $update = ["remark" => $remark, "solution" => $solution ?? ''];
                    $applyManagerDetail->update($update);

                    (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_2);

                    break;
                case WorkOrderUserRoleModel::ROLE_TYPE_7:

                    if (empty($remark)) {
//                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "备注不能为空");
                        $remark = "-";
                    }

                    if ($applyManagerDetail->remark) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "客服备注已提交，请勿反复操作！");
                    }

                    $update = ["remark" => $remark, "solution" => $solution ?? ''];
                    $applyManagerDetail->update($update);

                    (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_4);

                    break;
                default:
                    if (empty($remark)) {
//                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "备注不能为空");
                        $remark = "-";
                    }

                    if (empty($solution)) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "解决方案不能为空");
                    }

                    if ($applyManagerDetail->solution && $mainApply->problemChildId != OrderEnum::PROBLEM_PID_5_CHILDREN_105) {//夸父收银进件2.0可多次提交
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "解决方案已提交，请勿反复操作！");
                    }

                    if ($mainApply->step == MissionEnum::STEP_2) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "客服未提交备注，暂时不能提交");
                    }

                    $update = ["remark" => $remark, "solution" => $solution];
                    $applyManagerDetail->update($update);


                    // 所有负责人都提交了，推送任务
                    if (WorkOrderApplyManagerModel::query()
                                                  ->where("role", "<>", WorkOrderUserRoleModel::ROLE_TYPE_1)
                                                  ->where('workOrderNo', $workOrderNo)
                                                  ->where("status", WorkOrderApplyManagerModel::STATUS_ON)
                                                  ->get()
                                                  ->where('solution', '')
                                                  ->count() == 0) {
                        if ($mainApply->isFunctionWaiMaiOpen()) {
                            (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_5);
                        } else {
                            //富友自动进件
                            if ($mainApply->problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105) {
                                //判断是否是第一次提交-富友商户信息表
//                                $fuYouService = new FuYouService();
//                                $getInfo      = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($workOrderNo);
//                                if ($getInfo) {
//                                    $fuYouService->wxMchntUpd(['workOrderNo' => $workOrderNo, 'id' => $id, 'shopId' => $mainApply->shopId]);//商户信息更新接口
//                                } else {
//                                    $fuYouService->wxMchntAdd(['workOrderNo' => $workOrderNo, 'id' => $id, 'shopId' => $mainApply->shopId]);//商户信息登记接口
//                                }

                                dispatch((new FuYouAutoJob([
                                    'workOrderNo' => $workOrderNo,
                                    'id'          => $id,
                                    'shopId'      => $mainApply->shopId
                                ])))->onQueue('{fuyou-auto}');
                                break;
                            } else {
                                (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_4);
                            }
                        }
                        // 消息中心推送
                        $problemPidText     = $mainApply->problemPidText;
                        $problemChildIdText = $mainApply->problemChildIdText;

                        $title   = '您提交的工单已处理完成';
                        $summary = "尊敬的夸父伙伴您好，你提交的{$problemPidText}-{$problemChildIdText}工单，已处理完成，请点击查看详情。";
                        //$url = OrderEnum::getDetailUrl($mainApply);
//                        $notify = SystemNotifyService::save(
//                            false,
//                            $title,
//                            SystemNotifyCenterModel::NOTIFY_TYPE_3,
//                            SystemNotifyCenterModel::NOTIFY_TARGET_1,
//                            '',
//                            $title,
//                            '',
//                            SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
//                            $summary,
//                            '',
//                            SystemNotifyCenterModel::IS_POPUP_ON,
//                            '1'
//                        );
//                        SystemNotifyService::recordLog($notify, '创建消息');
//
//                        $manageShopList = array_values(array_column((RmsUserRemote::getShopManagerUserByShopId([$mainApply->shopId])['lists'] ?? []),
//                            null, 'userId'));
//
//                        foreach ($manageShopList as $value) {
//                            SystemNotifyService::preSend($notify->id, [$value['userId']]);
//                        }

                        $shopId    = $mainApply->shopId;
                        $fsMsgSend = function () use ($workOrderNo, $title, $summary, $shopId) {
                            $pushUidMap = array_values(
                                array_column(
                                    (RmsUserRemote::getShopManagerUserByShopId([$shopId])['lists'] ?? []),
                                    "userId"
                                )
                            );

                            SystemNotifyService::customerBatchPush(
                                $pushUidMap,
                                $title,
                                $summary,
                                config('webUrl.notify_web_cdn_url') . '#/pages/work-order/feedback/progress-detail?id=' . $workOrderNo,
                                $shopId,
                                SystemNotifyCenterModel::NOTIFY_TYPE_5
                            );
                        };

                        $fsMsgSend();
                    }
                    break;
            }

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 备注｜解决方案提交
     *
     * @param string $workOrderNo
     * @param int $userId
     * @param string $remark
     * @param string $solution
     * @return bool|void
     */
    public static function closeWorkOrder(string $workOrderNo, int $userId, string $remark, string $solution)
    {
        //获得目前流程处理角色
        $applyMainModel = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();
        $step           = $applyMainModel->step;
        if (in_array($step, [MissionEnum::STEP_99, MissionEnum::STEP_100])) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_REPEAT_CLOSE_WORK_ORDER));
        }
        //获得对应处理人角色
        $needRole = OrderListService::closeWorkOrderRole($applyMainModel,$userId);

        //查询是否有关闭权限
        $showClose = OrderListService::showClose($applyMainModel, $userId);
        if (!$showClose) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_CLOSE_WORK_ORDER));
        }

        //分为客服关闭与负责人关闭
        if ($needRole == WorkOrderUserRoleModel::ROLE_TYPE_1) {
            //客服关闭
            //主订单节点为已关闭
            $applyMainModel->status       = OrderEnum::MAIN_STATUS_CLOSE;
            $applyMainModel->step         = MissionEnum::STEP_100;
            $applyMainModel->completeTime = time();
            $res                          = $applyMainModel->save();


            $workOrderApplyManagerModel = WorkOrderApplyManagerModel::customFirstOrCreate(
                [
                    "workOrderNo" => $workOrderNo,
                    "role"        => WorkOrderUserRoleModel::ROLE_TYPE_1,
                    "managerId"   => $userId
                ],
                [
                    "workOrderNo" => $workOrderNo,
                    "status"      => WorkOrderApplyManagerModel::STATUS_ON,
                    "role"        => WorkOrderUserRoleModel::ROLE_TYPE_1,
                    "managerId"   => $userId,
                    "managerName" => getRequest()->user()->username,
                    "remark"      => $remark,
                    "solution"    => $solution,
                    "createdAt"   => time()
                ]
            );

            if ($workOrderApplyManagerModel->status != WorkOrderApplyManagerModel::STATUS_OFF) {
                $workOrderApplyManagerModel->update([
                    "remark"    => $remark,
                    "solution"  => $solution,
                    "updatedAt" => time()
                ]);
            }

            WorkOrderMissionModel::finish($workOrderNo, $step);

            (new SendSmsService($applyMainModel->workOrderNo))->workOrderApplyResult(false);

            return $res;
        }
        //非客服关闭

        //幂等返回
        $applyManagerModel = WorkOrderApplyManagerModel::query()
                                                       ->where('workOrderNo', $workOrderNo)
                                                       ->where('status', WorkOrderApplyManagerModel::STATUS_ON)
                                                       ->where('role', $needRole)
                                                       ->get();
        if (!count($applyManagerModel)) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_CLOSE_WORK_ORDER));
        }
        $selfHandle = $applyManagerModel->where('managerId', $userId)->where('role', $needRole)->first();
        if (null !== $selfHandle) {
            //关闭该负责人审批
            $selfHandle->status   = WorkOrderApplyManagerModel::STATUS_OFF;
            $selfHandle->remark   = $remark;
            $selfHandle->solution = $solution;
            $selfHandle->save();
            //负责人关闭工单飞书通知
            (new SendFsService($applyMainModel->workOrderNo))->personCloseWorkOrder($userId);

            //如果只有一位负责人 关闭订单
            if (count($applyManagerModel) == 1) {
                $applyMainModel->status       = OrderEnum::MAIN_STATUS_CLOSE;
                $applyMainModel->step         = MissionEnum::STEP_100;
                $applyMainModel->completeTime = time();
                $applyMainModel->save();

                // 任务关闭
                WorkOrderMissionModel::finish($workOrderNo, $step);

                // 飞书推送
                (new SendFsService($applyMainModel->workOrderNo))->workOrderApplyResult(false);

                // 短信推送
                (new SendSmsService($applyMainModel->workOrderNo))->workOrderApplyResult(false);
            }
        }
    }

    /**
     * 关闭订单
     *
     * @param object $params
     * @param int $uid
     * @return bool|void
     */
    public static function closeWorkOrderV2(object $params, int $uid)
    {
        //获得目前流程处理角色
        $applyMainModel = WorkOrderApplyMainModel::query()->where('workOrderNo', $params->workOrderNo)->first();
        $step           = $applyMainModel->step;
        //获得对应处理人角色
        $needRole = OrderListService::closeWorkOrderRole($applyMainModel,$uid);

        //查询是否有关闭权限
        $showClose = OrderListService::showClose($applyMainModel, $uid);
        if (!$showClose) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_CLOSE_WORK_ORDER));
        }


        //分为客服关闭与负责人关闭
        if ($needRole == WorkOrderUserRoleModel::ROLE_TYPE_1) {
            //客服关闭
            //主订单节点为已关闭
            $applyMainModel->status       = OrderEnum::MAIN_STATUS_CLOSE;
            $applyMainModel->step         = MissionEnum::STEP_100;
            $applyMainModel->completeTime = time();
            $res                          = $applyMainModel->save();

            WorkOrderOperateLogModel::generateOperateLog(
                $params->workOrderNo,
                $step,
                WorkOrderOperateLogModel::TYPE_11,
                request()->user()->username,
                request()->user()->id,
                $params->reason
            );
            WorkOrderMissionModel::finish($params->workOrderNo, $step);
            (new SendSmsService($applyMainModel->workOrderNo))->workOrderApplyResult(false);
            return $res;
        }

        //非客服关闭
        //幂等返回
        $applyManagerModel = WorkOrderApplyManagerModel::query()
                                                       ->where('workOrderNo', $params->workOrderNo)
                                                       ->where('status', WorkOrderApplyManagerModel::STATUS_ON)
                                                       ->where('role', $needRole)
                                                       ->get();
        if (!count($applyManagerModel)) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_CLOSE_WORK_ORDER));
        }
        $selfHandle = $applyManagerModel->where('managerId', $uid)->where('role', $needRole)->first();
        if (null !== $selfHandle) {
            //日志记录
            WorkOrderOperateLogModel::generateOperateLog(
                $params->workOrderNo,
                $step,
                WorkOrderOperateLogModel::TYPE_11,
                request()->user()->username,
                request()->user()->id,
                $params->reason
            );
            //关闭该负责人审批
            $selfHandle->status = WorkOrderApplyManagerModel::STATUS_OFF;
            $selfHandle->save();
            //负责人关闭工单飞书通知
            (new SendFsService($applyMainModel->workOrderNo))->personCloseWorkOrder($uid);
            //如果只有一位负责人 关闭订单
            if (count($applyManagerModel) == 1) {
                $applyMainModel->status       = OrderEnum::MAIN_STATUS_CLOSE;
                $applyMainModel->step         = MissionEnum::STEP_100;
                $applyMainModel->completeTime = time();
                $applyMainModel->save();
                // 任务关闭
                WorkOrderMissionModel::finish($params->workOrderNo, $step);
                // 飞书推送
                (new SendFsService($applyMainModel->workOrderNo))->workOrderApplyResult(false);
                // 短信推送
                (new SendSmsService($applyMainModel->workOrderNo))->workOrderApplyResult(false);
            }
        }
    }

    /**
     * @param string $workOrderNo
     * @param array $params
     * @param $userId
     * @return array|void
     * @throws Exception
     */
    public static function renew(
        string $workOrderNo,
        array $params,
        $userId
    ) {
        try {
            $applyMain = WorkOrderApplyMainModel::getDetailByWorkOrderNo($workOrderNo);
            switch ($applyMain->problemPid) {
                case OrderEnum::PROBLEM_PID_5:
                    $validateErrorFields = Form::submitFormByCompleteFields($workOrderNo, (object)$params);
                    break;
                case OrderEnum::PROBLEM_PID_1:
                case OrderEnum::PROBLEM_PID_2:
                case OrderEnum::PROBLEM_PID_4:
                case OrderEnum::PROBLEM_PID_6:
                case OrderEnum::PROBLEM_PID_7:
                case OrderEnum::PROBLEM_PID_8:
                case OrderEnum::PROBLEM_PID_9:
                case OrderEnum::PROBLEM_PID_10:
                    $validateErrorFields = ProblemFeedbackWebService::renewByProblemFeedback($workOrderNo, $params,
                        $userId, $applyMain->problemPid);
                    break;
                default:
                    throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null,
                        "未配置的表单分类体 【{$applyMain->problemPid}】");
            }

            return [
                "validateErrorFields" => $validateErrorFields
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 工单转交
     *
     * @param string $workOrderNo
     * @param int $managerId
     * @param int $userId
     * @return void
     */
    public static function circulation(string $workOrderNo, int $managerId, int $userId)
    {
        //获得目前流程处理角色
        $applyMainModel = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();
        $step           = $applyMainModel->step;
        if (in_array($step, [MissionEnum::STEP_99, MissionEnum::STEP_100])) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_CIRCULATION_OFF));
        }
        //获得对应处理人角色
        if (in_array($step, [MissionEnum::STEP_1, MissionEnum::STEP_2, MissionEnum::STEP_3])) {
            $needRole = WorkOrderUserRoleModel::ROLE_TYPE_1;
        } else {
            $needRole = OrderEnum::PROBLEM_PID_TO_ROLE[$applyMainModel->problemPid] ?? 0;
        }

        //判断改用户是否能够流转
        $applyManagerModel = WorkOrderApplyManagerModel::query()
                                                       ->where('workOrderNo', $workOrderNo)
                                                       ->where('role', $needRole)
                                                       ->where('managerId', $userId)
                                                       ->first();

        if (null === $applyManagerModel) {
            //不可以流转
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_CIRCULATION_OFF));
        }
        DB::beginTransaction();
        try {
            $applyManagerModel->status = WorkOrderApplyManagerModel::STATUS_OFF;
            $applyManagerModel->save();

            //新增负责人

            $managerName = (string)WorkOrderUserRoleModel::query()->where('userId', $managerId)->value('name');
            $handleArr   = [
                'workOrderNo' => $workOrderNo,
                'role'        => OrderEnum::PROBLEM_PID_TO_ROLE[$applyMainModel->problemPid] ?? 0,
                'managerId'   => $managerId,
                'managerName' => $managerName,
                'remark'      => '',
                'status'      => WorkOrderApplyManagerModel::STATUS_ON,
                'solution'    => '',
            ];
            WorkOrderApplyManagerModel::query()->create($handleArr);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::info('工单转交失败' . $exception->getMessage());
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_UPDATE_WORK_ORDER));
        }

    }

    /**
     * 获取门店套图列表
     * @return array
     */
    public static function getShopImg(): array
    {
        return json_decode(
            ConfigModel::query()
                       ->where('module', 'fuyou')
                       ->where('name', ConfigModel::FUYOU_SHOP_IMG)
                       ->value('value') ?? '', true
        );
    }

    /**
     * 修改门店套图列表
     * @param $request
     * @throws Exception
     */
    public static function updateShopImg($request)
    {
        try {
            $data = [
                'shopImg' => json_encode([
                    'doorHeaderImg' => $request->doorHeaderImg,
                    'frontImg'      => $request->frontImg
                ]),//店铺审核图片 doorHeaderImg-门头照 frontImg-门脸照
            ];
            WorkOrderFuyouInfoModel::setInfoById($request->id, $data);
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 富友进件2.0-修改富友平台审核信息
     * @param $request
     * @param int $flagSuc 0-只编辑信息 1-工单状态-完成
     * @throws Exception
     */
    public static function updateFuyouInfo($request, $flagSuc = 0)
    {
        try {
            $workOrderNo = WorkOrderFuyouInfoModel::getInfoById($request->id)['workOrderNo'];
            if (!$workOrderNo) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_WORK_ORDER_NO));
            }
            if (!$flagSuc) {//只编辑信息
                $data = [
                    'fyMchntCd'        => $request->mchId,                 //富友商户号
                    'mchKey'           => $request->mchKey ?? '',          //富友商户交易密码
                    'orderPrefix'      => $request->orderPrefix ?? '',     //富友商户交易前缀
                    'mchName'          => $request->mchName,               //富友用户名
                    'mchPassword'      => $request->mchPassword,           //富友密码
                    'reservedFyTermId' => $request->reservedFyTermId ?? "",//富友终端号
                ];
                WorkOrderFuyouInfoModel::setInfoById($request->id, $data);
            } else {//工单状态-完成
                $applyMainModel = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();
                if ($applyMainModel->step < MissionEnum::STEP_7) {//非这个阶段不能修改
                    throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_NOT_STEP_UPDATE_DATA));
                }
                $data['workOrderNo'] = $workOrderNo;
                FuYouService::updateWorkOrder($data, $data, 200, '完成', WorkOrderFuyouInfoModel::DEFAULT_STEP_SUC,
                    WorkOrderFuyouLogModel::DEFAULT_SUC_STATUS, MissionEnum::STEP_8);
                (new MissionEngineService($data['workOrderNo']))->finish(MissionEnum::STEP_8);
            }
        } catch (Exception $exception) {
            handleException($exception);
        }
    }


    /**
     * 富友进件2.0-重新发送邮件
     * @param int $id 富友商户信息表id
     * @param int $type 类型1-重新发送一二级绑定邮件 2-重新发送前置系统申请邮件
     * @throws Exception
     */
    public static function sendFuyouEmail(int $id, int $type)
    {
        try {
            $fyInfo = WorkOrderFuyouInfoModel::getInfoById($id);
            if (!$fyInfo) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_NOT_FOUND_FY_INFO));
            }
            if (!$fyInfo['workOrderNo']) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_WORK_ORDER_NO));
            }
            if ($type == self::SEND_EMAIL_TYPE_SECONDARY_BINDING && $fyInfo['secondaryBindingStatus'] != WorkOrderFuyouInfoModel::DEFAULT_SYSTEM_APPLY_STATUS) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_EXIST_SEND_EMAIL));
            }
            if ($type == self::SEND_EMAIL_TYPE_SYSTEM_APPLY && $fyInfo['preSystemApplyStatus'] != WorkOrderFuyouInfoModel::DEFAULT_SYSTEM_APPLY_STATUS) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_EXIST_SEND_EMAIL));
            }
            /*$applyMainModel = WorkOrderApplyMainModel::query()->where('workOrderNo', $fyInfo['workOrderNo'])->first();
            if ($applyMainModel->step != MissionEnum::STEP_8) {//非这个阶段不能重新发送邮件
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_NOT_STEP_UPDATE_DATA));
            }*/
            dispatch(
                (new FuYouSendEmailAutoJob(
                    [
                        'workOrderNo' => $fyInfo['workOrderNo'],
                        'companyName' => $fyInfo['companyName'],
                        'fyMchntCd'   => $fyInfo['fyMchntCd'],
                        'type'        => $type,
                    ]
                ))
            )->onQueue('{fuyou-send-email-auto}');
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 解绑功能开通
     * @param int $shopId
     * @param array $problemChildIds
     * @param int $unbind
     * @param int $userId
     * @param string $userName
     * @param int $type
     * @return void
     * @throws GuzzleException
     */
    public static function resetFunctionOpen(
        int $shopId,
        array $problemChildIds,
        int $unbind,
        int $userId,
        string $userName,
        int $type = 0
    ): void {
        Log::info("resetFunctionOpenLog shopId:{$shopId}", $problemChildIds);
        $reason = '功能开通重置';
        if ($type) {
            $reason = '门店迁址-' . $reason;
        }
        // 进行中的功能开通功能关闭
        WorkOrderApplyMainModel::query()
                               ->where('shopId', $shopId)
                               ->where('problemPid', OrderEnum::PROBLEM_PID_5)
                               ->whereIn('problemChildId', $problemChildIds)
                               ->whereIn('status', [OrderEnum::MAIN_STATUS_ING, OrderEnum::MAIN_STATUS_FINISH, OrderEnum::MAIN_STATUS_CLOSE])
                               ->get()
                               ->each(function ($item) use ($reason, $userId, $userName) {
                                   /* 功能开通重置 工单记录不做删除，状态设置为关闭
                                    * WorkOrderApplyManagerModel::query()->where('workOrderNo', $item->workOrderNo)
                                                             ->update(['isDeleted' => 1]);
                                   WorkOrderMissionModel::query()->where('workOrderNo', $item->workOrderNo)
                                                        ->update(['isDeleted' => 1]);*/

//                                   if ($item->step != MissionEnum::STEP_100) {
                                       $item->status    = OrderEnum::MAIN_STATUS_CLOSE;// 已关闭
                                       $item->step      = MissionEnum::STEP_100;       // 关闭
                                       $item->isDeleted = 1;
                                       $item->save();

                                       WorkOrderOperateLogModel::generateOperateLog(
                                           $item->workOrderNo,
                                           MissionEnum::STEP_100,
                                           WorkOrderOperateLogModel::TYPE_16,
                                           $userName,
                                           $userId,
                                           $reason
                                       );
//                                   }
                               });

        // rms取消绑定
        if ($unbind) {

            // 夸父收银
            if (in_array(OrderEnum::PROBLEM_PID_5_CHILDREN_100, $problemChildIds)) {
                (new RmsShopApi())->unbindFy($shopId);
            }

            // 美团外卖
            if (in_array(OrderEnum::PROBLEM_PID_5_CHILDREN_101, $problemChildIds)) {
                (new RmsShopApi())->unbindFunctionOpen($shopId, RmsShopApi::SOURCE_TYPE_WM_MT);
            }

            // 饿了么外卖
            if (in_array(OrderEnum::PROBLEM_PID_5_CHILDREN_102, $problemChildIds)) {
                (new RmsShopApi())->unbindFunctionOpen($shopId, RmsShopApi::SOURCE_TYPE_WM_ELM);
            }

            // 点评
            if (in_array(OrderEnum::PROBLEM_PID_5_CHILDREN_103, $problemChildIds)) {
                (new RmsShopApi())->unbindFunctionOpen($shopId, RmsShopApi::SOURCE_TYPE_DP);
            }

            // 抖音
            if (in_array(OrderEnum::PROBLEM_PID_5_CHILDREN_104, $problemChildIds)) {
                (new RmsShopApi())->unbindFunctionOpen($shopId, RmsShopApi::SOURCE_TYPE_DY);
            }
        }

        // 重置记录
        WorkOrderResetModel::batchAddData(collect($problemChildIds)->map(function ($problemChildId) use (
            $shopId,
            $unbind
        ) {
            return [
                'shopId'         => $shopId,
                'problemChildId' => $problemChildId,
                'unbind'         => $unbind,
            ];
        }));

        // 日志记录
        $changes = json_encode([
            [
                "theme"      => "功能开通重置",
                "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_INSERT,
                "data"       => [
                    [
                        "key"         => "text",
                        "beforeValue" => 1,
                        "afterValue"  => 0,
                        "beforeText"  => "开通",
                        "afterText"   => "未开通",
                        "type"        => ChangeSupport::FILED_TYPE_STRING,
                        "description" => collect($problemChildIds)->map(function ($item) {
                            return OrderEnum::FUNCTION_OPEN[$item] ?? '';
                        })->implode(','),
                    ]
                ]
            ]
        ], JSON_UNESCAPED_UNICODE);

        $orderNo = (string)OpenShopMainProcessModel::query()->where('shopId', $shopId)->orderByDesc('id')
                                                   ->value('orderNo');

        OpenShopSignOrderLogModel::logInsert(
            OpenShopSignOrderModel::query()->where("orderNo", $orderNo)->first()->id,
            OpenShopSignOrderLogModel::SKIP_STEP_UNBIND_FUNCTION_OPEN,
            $userName,
            $userId,
            $changes
        );
    }

    /**
     * 富友进件2.0-新增富友平台审核信息
     * @param $request
     * @param int $flagSuc 0-只编辑信息 1-工单状态-完成
     * @param string $workOrderNo
     * @throws ValidationException
     */
    public static function addFuyouInfo($request, $flagSuc = 0, $workOrderNo = '')
    {
        try {
            if (!$workOrderNo) {
                $workOrderNo = $request->workOrderNo;
            }
            $applyMainModel = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();
            if (!$workOrderNo || !$applyMainModel) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_WORK_ORDER_NO));
            }
            if (!$flagSuc) {//只编辑信息
                $data = [
                    'workOrderNo'      => $workOrderNo,                    //工单号
                    'fyMchntCd'        => $request->mchId,                 //富友商户号
                    'mchKey'           => $request->mchKey ?? '',          //富友商户交易密码
                    'orderPrefix'      => $request->orderPrefix ?? '',     //富友商户交易前缀
                    'mchName'          => $request->mchName,               //富友用户名
                    'mchPassword'      => $request->mchPassword,           //富友密码
                    'reservedFyTermId' => $request->reservedFyTermId ?? "",//富友终端号
                ];
                WorkOrderFuyouInfoModel::addInfo($data);
            } else {//工单状态-完成
                if ($applyMainModel->step < MissionEnum::STEP_7) {//非这个阶段不能修改
                    throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_NOT_STEP_UPDATE_DATA));
                }
                $data['workOrderNo'] = $workOrderNo;
                FuYouService::updateWorkOrder($data, $data, 200, '完成', WorkOrderFuyouInfoModel::DEFAULT_STEP_SUC,
                    WorkOrderFuyouLogModel::DEFAULT_SUC_STATUS, MissionEnum::STEP_8);
                (new MissionEngineService($data['workOrderNo']))->finish(MissionEnum::STEP_8);
            }
        } catch (Exception $exception) {
            handleException($exception);
        }
    }
}
